package com.soujiayi.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.soujiayi.net.NetworkUtils;
import com.soujiayi.share.SinaWeiboAPI;
import com.soujiayi.store.DatabaseManager;
import com.soujiayi.util.Constants;
import com.soujiayi.util.UserKeeper;
import com.soujiayi.weibo.User;
import com.tencent.weibo.oauthv2.OAuthV2;
import com.tencent.weibo.oauthv2.OAuthV2Client;
import com.tencent.weibo.webview.OAuthV2AuthorizeWebView;

public class ShareSettingActivity extends Activity {

	private Handler handler;
	private DatabaseManager databaseManager = new DatabaseManager(ShareSettingActivity.this);
	private TextView tv_share_sinaweibo_unbind;
	private TextView tv_share_tencentweibo_unbind;
	private ImageView iv_share_sinaweibo_bind;
	private ImageView iv_share_tencentweibo_bind;

	// Tencent weibo
    public OAuthV2 tencent_oAuth;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		((MyApplication) this.getApplication()).addActivity(this);
		setContentView(R.layout.share_setting);

		tv_share_sinaweibo_unbind = (TextView) findViewById(R.id.tv_share_sinaweibo_unbind);
		tv_share_tencentweibo_unbind = (TextView) findViewById(R.id.tv_share_tencentweibo_unbind);
		iv_share_sinaweibo_bind = (ImageView) findViewById(R.id.iv_share_sinaweibo_bind);
		iv_share_tencentweibo_bind = (ImageView) findViewById(R.id.iv_share_tencentweibo_bind);
		
		handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {
				super.handleMessage(msg);
				Bundle data = msg.getData();
				 boolean isSuccess = data.getBoolean("isSuccess", false);
				if(isSuccess){
					User user = (User) data.getSerializable(Constants.SETTINGS_USER_KEY);	
					if(user.getType() == Constants.USER_TYPE_SINA){
						tv_share_sinaweibo_unbind.setVisibility(View.GONE);
						iv_share_sinaweibo_bind.setVisibility(View.VISIBLE);
						UserKeeper.keepUser(ShareSettingActivity.this, user, Constants.PREFERENCES_NAME_USER_SINA);
						databaseManager.insertShareUser(user);
					}

				}else{
					Toast.makeText(
							ShareSettingActivity.this,
							ShareSettingActivity.this.getResources().getString(
									R.string.share_setting_failure),
							Toast.LENGTH_SHORT).show();
				}
			}
		};
	}
	
	public void bindSina(View view) {
		User user  = UserKeeper.readUser(this, Constants.PREFERENCES_NAME_USER_SINA);
		if(user != null){
			tv_share_sinaweibo_unbind.setVisibility(View.VISIBLE);
			iv_share_sinaweibo_bind.setVisibility(View.GONE);
			UserKeeper.clear(this, Constants.PREFERENCES_NAME_USER_SINA);
			databaseManager.deleteShareUser(user.getType());
		}else{
			if (NetworkUtils.isNetworkConnected(this)){
				SinaWeiboAPI sinaWeiboAPI = new SinaWeiboAPI(this, handler);
				sinaWeiboAPI.login();
			}else{
				Toast.makeText(
						this,
						this.getResources().getString(
								R.string.network_unavailable_message),
						Toast.LENGTH_SHORT).show();
			}
		}
	}
	
	public void bindTencent(View view) {
		User user  = UserKeeper.readUser(this, Constants.PREFERENCES_NAME_USER_TENCENT);
		if(user != null){
			tv_share_tencentweibo_unbind.setVisibility(View.VISIBLE);
			iv_share_tencentweibo_bind.setVisibility(View.GONE);
			UserKeeper.clear(this, Constants.PREFERENCES_NAME_USER_TENCENT);
			databaseManager.deleteShareUser(user.getType());
		}else{
			if (NetworkUtils.isNetworkConnected(this)){
				tencentLogin();
			}else{
				Toast.makeText(
						this,
						this.getResources().getString(
								R.string.network_unavailable_message),
						Toast.LENGTH_SHORT).show();
			}
		}
	}
	
	public void tencentLogin(){
		if(tencent_oAuth == null){
			tencent_oAuth=new OAuthV2(Constants.TENCENT_REDIRECT_URL);
			tencent_oAuth.setClientId(Constants.TENCENT_CLIENT_ID);
			tencent_oAuth.setClientSecret(Constants.TENCENT_CLIENT_SECRET);
	        
	        //关闭OAuthV2Client中的默认开启的QHttpClient。
	        OAuthV2Client.getQHttpClient().shutdownConnection();
		}
        Intent intent = new Intent(this, OAuthV2AuthorizeWebView.class);
        intent.putExtra("oauth", tencent_oAuth);
        startActivityForResult(intent,2);  
	}
	
    protected void onActivityResult(int requestCode, int resultCode, Intent data)   {
    	boolean isSuccess = false;
        if (requestCode==2) {
            if (resultCode==OAuthV2AuthorizeWebView.RESULT_CODE)    {
               	tencent_oAuth = (OAuthV2) data.getExtras().getSerializable("oauth");
                if(tencent_oAuth.getStatus()==0){
                	isSuccess = true;
                	User user = new User();
    				user.setType(Constants.USER_TYPE_TENCENT);
    				user.setTencent_token(tencent_oAuth.getAccessToken());
    				user.setTencent_clientId(tencent_oAuth.getClientId());
    				user.setTencent_clientIp(tencent_oAuth.getClientIP());
    				user.setTencent_clientSecret(tencent_oAuth.getClientSecret());
    				user.setTencent_oauthVersion(tencent_oAuth.getOauthVersion());
    				user.setTencent_openid(tencent_oAuth.getOpenid());
    				user.setTencent_openkey(tencent_oAuth.getOpenkey());
    				user.setTencent_redirectUri(tencent_oAuth.getRedirectUri());
    				user.setTencent_scope(tencent_oAuth.getScope());
    				user.setTencent_expires_in(tencent_oAuth.getExpiresIn());
    				user.setTencent_expires_time(String.valueOf(System.currentTimeMillis() + Long.parseLong(tencent_oAuth.getExpiresIn())*1000));
    				

					tv_share_tencentweibo_unbind.setVisibility(View.GONE);
					iv_share_tencentweibo_bind.setVisibility(View.VISIBLE);
	    				UserKeeper.keepUser(ShareSettingActivity.this, user, Constants.PREFERENCES_NAME_USER_TENCENT);
	    			databaseManager.insertShareUser(user);
                }
            }
        }
        if(!isSuccess){
			Toast.makeText(
					ShareSettingActivity.this,
					ShareSettingActivity.this.getResources().getString(
							R.string.share_setting_failure),
					Toast.LENGTH_SHORT).show();
        }
    }

	public void back(View view) {
		this.finish();
		overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
	}
	
	@Override
	protected void onResume() {
		User sinaUser = UserKeeper.readUser(this, Constants.PREFERENCES_NAME_USER_SINA);
		User tencentUser = UserKeeper.readUser(this, Constants.PREFERENCES_NAME_USER_TENCENT);
		if(sinaUser != null){
			tv_share_sinaweibo_unbind.setVisibility(View.GONE);
			iv_share_sinaweibo_bind.setVisibility(View.VISIBLE);
		}else{
			tv_share_sinaweibo_unbind.setVisibility(View.VISIBLE);
			iv_share_sinaweibo_bind.setVisibility(View.GONE);
		}
		if(tencentUser != null){
			tv_share_tencentweibo_unbind.setVisibility(View.GONE);
			iv_share_tencentweibo_bind.setVisibility(View.VISIBLE);
		}else{
			tv_share_tencentweibo_unbind.setVisibility(View.VISIBLE);
			iv_share_tencentweibo_bind.setVisibility(View.GONE);
		}
		super.onResume();
	}
	
	@Override
	protected void onDestroy() {
		databaseManager.closeDB();
		super.onDestroy();
	}
	
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		//如果按下的是返回键，并且没有重复
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			finish();
			overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out);
			return false;
		}
		return false;
	}

}
